package com.mvp.lt.airlineview.utils.TTs;

import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.ToastUtils;

import java.util.Locale;

/**
 * @author LiuTao
 * @description:
 * @date : 2021/1/8 15:03
 */
public class TextToSpeechUtils {
    private Context mContext;
    private TextToSpeech mTextToSpeech;
    private static TextToSpeechUtils sTextToSpeechUtils;

    public static TextToSpeechUtils getInstance(Context context) {
        if (sTextToSpeechUtils == null) {
            sTextToSpeechUtils = new TextToSpeechUtils(context);
        }
        return sTextToSpeechUtils;
    }

    private TextToSpeechUtils(Context context) {
        this.mContext = context;

    }

    public void initSpeak() {
        mTextToSpeech = new TextToSpeech(mContext, new listener());
    }

    private class listener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                mTextToSpeech.setPitch(10.0f);
                mTextToSpeech.setSpeechRate(0.5f);
                //设置播放语言
                int result = mTextToSpeech.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    LogUtil.e("播放", "不支持");
                } else if (result == TextToSpeech.LANG_AVAILABLE) {
                    LogUtil.e("播放", "正在初始化");
                    //初始化成功之后才可以播放文字
                    //否则会提示“speak failed: not bound to tts engine
                    //TextToSpeech.QUEUE_ADD会将加入队列的待播报文字按顺序播放
                    //TextToSpeech.QUEUE_FLUSH会替换原有文字

                }
            } else {
                Log.e("TAG", "初始化失败");
            }
        }
    }


    public void speak(String msg) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mTextToSpeech.speak(msg, TextToSpeech.QUEUE_FLUSH, null, "");
        } else {
            mTextToSpeech.speak("English", TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    public void stopTextToSpeech() {
        if (mTextToSpeech != null) {
            mTextToSpeech.shutdown();
            mTextToSpeech.stop();
            mTextToSpeech = null;
        }
    }

}
